package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 根据微信官方提供的接口文档进行开发
 * @author ghy
 * @version 1.0
 * @since 2025-08-20 09:39
 */
@Service
public class WechatServiceImpl implements WechatService {

    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;


    /**
     * 根据code获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        // 通过HttpUtil发起小程序登录接口的远程调用
        try {
            Map<String, Object> params = getAppIdAndSecret();
            params.put("js_code", code);
            String result = HttpUtil.get(REQUEST_URL, params);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (ObjUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
                throw new BaseException("获取微信openId失败", jsonObject.getStr("errmsg"));
            }
            // 成功：{"session_key":"oL7v82zrwGnMjEkFHaQ/lw==","openid":"oVJ_I6Nb8oqyPlq4DEQFCDxAFEWc"}
            // code只能使用一次：{"errcode":40163,"errmsg":"code been used, rid: 68a52b8a-26789422-5d6a7990"}
            // appid错误：{"errcode":40013,"errmsg":"invalid appid, rid: 68a52bec-1edddf48-5afca239"}
            // secret错误：{"errcode":40125,"errmsg":"invalid appsecret, rid: 68a52c26-728d1dfb-2e21cd69"}
            return jsonObject.getStr("openid");
        } catch (Exception e) {
            throw new BaseException("网络繁忙，请稍后重试", e.getMessage());
        }
    }

    /**
     * 根据code获取手机号
     *
     * @param code
     * @return
     */
    @Override
    public String getPhone(String code) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("code", code);
            String result = HttpUtil.post(PHONE_REQUEST_URL + getAccessToken(), JSONUtil.toJsonStr(params));
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (jsonObject.getInt("errcode") != 0) {
                throw new BaseException("获取手机号失败", jsonObject.getStr("errmsg"));
            }
            return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        } catch (BaseException e) {
            throw new BaseException("网络繁忙，请稍后重试", e.getMessage());
        }
    }

    /**
     * 获取手机号需要的access_token
     *
     * @return
     */
    @Override
    public String getAccessToken() {
        try {
            Map<String, Object> params = getAppIdAndSecret();
            String result = HttpUtil.get(TOKEN_URL, params);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String accessToken = jsonObject.getStr("access_token");
            if(StringUtils.isBlank(accessToken)) {
                throw new BaseException("获取AccessToken失败");
            }
            return accessToken;
        } catch (Exception e) {
            throw new BaseException("网络繁忙，请稍后重试", e.getMessage());
        }
    }

    private Map<String, Object> getAppIdAndSecret() {
        Map<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        return params;
    }


}
